﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Jumpton.Persistent;
using Jumpton.SFA.Server.Entity;

namespace Jumpton.SFA.Server.BusinessRule.System
{
    public class UserManager : BusinessLogic
    {

        #region 创建用户
        /// <summary>
        /// 创建用户
        /// </summary>
        /// <param name="code"></param>
        /// <param name="pwd"></param>
        /// <param name="personID"></param>
        /// <param name="groupID"></param>
        /// <param name="rights"></param>
        /// <param name="domainID"></param>
        /// <param name="createBy"></param>
        /// <returns></returns>
        public static decimal CreateUser(string code, string pwd, decimal personID, decimal groupID,int orgID, string rights, decimal domainID, string createBy)
        {
            USERS user = new USERS();
          
            user.CODE = code;
            user.PASSWORD = pwd;
            user.PERSONID = personID;
            user.GROUPID = groupID;
            user.RIGHTS = rights;
            user.DOMAINID = domainID;
            user.LAST_UPDATER = createBy;
            user.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
            user.FORCEEXPORTALL = "N";
            user.ISLOCK = false;
            user.FAILLOGINCOUNT = "0";
            user.ACTIVE = true;
            user.ORGID = orgID;

            try
            {
                user.Save();
                return user.ID;
            }
            catch (Exception err)
            {
                throw new Exception(err.Message);
                return decimal.MinValue;
            }

        }
        #endregion

        #region 根据用户帐号获取登录信息
        /// <summary>
        /// 根据用户帐号获取登录信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="domainID"></param>
        /// <returns></returns>
        public DataTable GetUserByCode(string code, string domainID)
        {
            string str = @"select USERS.ID,USERS.CODE,NAME,position,USER_GROUPS.CODE 'Group_Name'
                            from USERS inner join PERSONS
	                            on USERS.PERSON_ID=PERSONS.ID inner join USER_GROUPS
	                            on USERS.GROUP_ID=USER_GROUPS.ID where USERS.DOMAIN_ID='" + domainID + "' ";

            if (!string.IsNullOrEmpty(code))
                str += " and USERS.CODE like '%" + code + "%'";

            str += " order by USERS.LAST_UPDATE_TIME desc";

            return Jumpton.Data.SqlData.OpenSql(str).Tables[0];
        }
        #endregion

        #region 根据用户帐号获取登录信息
        /// <summary>
        /// 根据用户帐号获取登录信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="domainID"></param>
        /// <returns></returns>
        public USERS GetUserByCode(string code)
        {
            return (USERS)ObjectRow.Load(typeof(USERS), "this.CODE='" + code + "' ");
        }
      
        #endregion

        #region 是否存在同名帐号
        /// <summary>
        /// 是否存在同名帐号
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool IsExistsUser(string name)
        {
            USERS user = (USERS)ObjectRow.Load(typeof(USERS), "this.CODE='" + name + "'");
            if (user != null)
                return true;
            else
                return false;

        }
        #endregion

     

        #region 登录是否成功
        public static USERS IsLoginPass(string name, string pwd)
        {
            pwd = Jumpton.Common.Functions.EncryptString(pwd);
            USERS user = (USERS)ObjectRow.Load(typeof(USERS), "this.CODE='" + name + "'");
            if (user != null && user.ACTIVE && pwd == user.PASSWORD)
                return user;
            return null;
        }
        #endregion

        #region 获取没有设移动端的用户的帐号
        /// <summary>
        /// 获取没有设移动端的用户的帐号
        /// </summary>
        /// <param name="domainID"></param>
        /// <returns></returns>
        public DataTable GetUserWithNoMobile(decimal domainID, int orgID)
        {
            StringBuilder sql = new StringBuilder();
            sql.Append("select ID,CODE from USERS where ID not in ");
            sql.AppendFormat(" (select USER_ID from MOBILE_USERS where DOMAIN_ID='{0}') and DOMAIN_ID='{0}' and ORG_ID IN (select ID from [FC_GetOrgWithParentID]('{0}','{1}')) order by code", domainID, orgID);

            return Jumpton.Data.SqlData.OpenSql(sql.ToString()).Tables[0];
        }
        #endregion

        #region 修改密码
        public bool ChangePassword(decimal userID, string pwd)
        {
            USERS user = GetUserByID(userID);
            user.PASSWORD = Jumpton.Common.Functions.EncryptString(pwd);
            user.UserToken = Common.Functions.EncryptString(user.CODE + user.PASSWORD);
            try
            {
                user.Save();
                return true;
            }
            catch (Exception error)
            {
                throw new Exception(error.Message);
                return false;
            }
        }
        #endregion

        public USERS GetUserByPersonID(decimal ID)
        {
            return (USERS)ObjectRow.Load(typeof(USERS), "this.PERSONID='" + ID + "' and this.ACTIVE=1");
        }


        public USERS GetUserByID(decimal ID)
        {
            return (USERS)ObjectRow.Load(typeof(USERS), "this.ID='" + ID + "'");
        }

        public DataTable GetAllUsersForDDL(decimal domainID, string orgValues)
        {
            if (orgValues != "")
            {
                string Query = string.Format(@"SELECT DISTINCT USERS.ID,
		                                                    USERS.CODE AS USER_CODE,
		                                                    PERSONS.NAME AS CODENAME,
                                                            Users.Org_Id
                                                    FROM USERS
                                                        INNER JOIN PERSONS ON PERSONS.ID = USERS.PERSON_ID
                                                    WHERE USERS.DOMAIN_ID = {0}
                                                        AND USERS.ORG_ID IN ({1})
                                                    ORDER BY USERS.CODE", domainID, orgValues);
                return Jumpton.Data.SqlData.OpenSql(Query).Tables[0];
            }
            else
                return null;
        }

        public ObjectTable GetAllUserTable(decimal domainid)
        {
            return new ObjectTable(typeof(USERS), "this.DOMAINID='" + domainid + "'");
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="loginCode"></param>
        /// <param name="name"></param>
        /// <param name="position"></param>
        /// <param name="domainId"></param>
        /// <param name="orgID"></param>
        /// <param name="groupid">如果选择所有请填写 '0'</param>
        /// <returns></returns>
        public static DataSet SelectUserDynamic(string loginCode,
                                                string name,
                                                string position,
                                                decimal domainId,
                                                string orgID,
                                                string kind,
                                                decimal groupid)
        {
            return Jumpton.Data.SqlData.OpenSP("sp_SelectUSERSsDynamic", loginCode,
                                                name,
                                                position,
                                                domainId,
                                                orgID,
                                                kind,
                                                groupid);
        }


        public static DataSet SelectUserThridPartyCom(string code,string name,string position,
                                        decimal domainid, string role,decimal tpcid)
        {     
            return Jumpton.Data.SqlData.OpenSP("sp_SelectUSERSsThridPartyCom", code,
                                                name,
                                                position, 
                                                role,
                                                tpcid.ToString(),
                                                domainid.ToString());
        }

         public static DataSet SelectUserDynamicForExcel(string loginCode,
                                                string name,
                                                string position,
                                                decimal domainId,
                                                string orgID,
                                                decimal groupid)
        {
            return Jumpton.Data.SqlData.OpenSP("sp_SelectUSERSsDynamicForExcel", loginCode,
                                                name,
                                                position,
                                                domainId,
                                                orgID,
                                                groupid);
        }

        public void AddChainsForUser(decimal userID, int chainID, string creater)
        {
            USER_CHAINS userChains = LoadChainsByUser(userID);

            if (userChains == null)
                userChains = new USER_CHAINS();

            userChains.USERID = userID;
            userChains.CHAINSID = chainID;
            userChains.LAST_UPDATE_TIME = BusinessLogic.GetDateTimeDecimal(DateTime.Now);
            userChains.LAST_UPDATER = creater;
            userChains.Save();
        }

        public void DeleteChainsForUser(decimal userID)
        {
            USER_CHAINS userChains = LoadChainsByUser(userID);

            if (userChains != null)
                userChains.Delete();
        }


        public USER_CHAINS LoadChainsByUser(decimal userID)
        {
            return (USER_CHAINS)ObjectRow.Load(typeof(USER_CHAINS), "this.USERID='" + userID + "'");

        }

        public DataSet LoadUserByPhoneNumber(string phoneNumber)
        {
            string Query = string.Format(@"SELECT U.ORG_ID,U.ID AS USER_ID FROM PERSONS P 
                                        INNER JOIN USERS U  ON U.PERSON_ID = P.ID
                                        WHERE P.TELEPHONE='{0}'", phoneNumber);
            return Jumpton.Data.SqlData.OpenSql(Query);
        }


        #region 保存
        /// <summary>
        /// 保存User
        /// </summary>
        /// <param name="user"></param>
        public bool Save(USERS user)
        {
            bool success = false;
            if (user != null)
            {
                try
                {
                   

                    //判断是否有同名帐号
                    USERS obj = ObjectRow.Load(typeof(USERS), string.Format("this.CODE='{0}'", user.CODE)) as USERS;
                    if (obj != null && obj.ID != user.ID)
                    {
                        throw new Exception("存在同名帐号");
                    }
                    user.Save();
                    success = true;
                }
                catch (Exception error)
                {
                    throw new Exception(error.Message);
                }
            }
            return success;
        }
        #endregion

        public static bool IsAdmin(decimal userID, string admincode, decimal domainid)
        {
            string sql = @"SELECT USERS.ID,USER_GROUPS.CODE FROM USERS 
                        INNER JOIN SYS_USER_ROLES  ON SYS_USER_ROLES.User_ID = USERS.ID
                        INNER JOIN USER_GROUPS ON SYS_USER_ROLES.ROLE_NO = USER_GROUPS.ID
                        WHERE USERS.ID=" + userID.ToString() + " AND USER_GROUPS.CODE='" + admincode + "' AND USERS.DOMAIN_ID=" + domainid.ToString();
            DataSet ds = Jumpton.Data.SqlData.OpenSql(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }


        }

        /// <summary>
        /// 根据用户选择的组织结构获取该结构下面的所有业代
        /// </summary>
        /// <param name="orgName"></param>
        /// <param name="domainID"></param>
        /// <returns></returns>
        public DataTable GetUserTableByOrgName(string orgName, decimal domainID)
        {
            string sql = string.Format(@"select u.ID UserId,p.name PersonName from users u 
                    inner join mobile_users mu on u.id=mu.user_id 
                    inner join persons p on p.id=u.person_id
                    where u.org_id in (select id from organization where name='{0}') and u.domain_id={1}", orgName, domainID);

            return Jumpton.Data.SqlData.OpenSql(sql).Tables[0];
        }

        public bool isManager(decimal personid)
        {
            string sql = @"select ID from USERS where person_id in(select ID from PERSONS where MANAGER_ID='" + personid + "' );";
            DataSet ds = Jumpton.Data.SqlData.OpenSql(sql);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取所有子部门
        /// </summary>
        /// <param name="orgid">部门id</param>
        /// <param name="domain_id">域id</param>
        /// <param name="flag">是否包涵的当前部门</param>
        /// <returns>返回部门表</returns>
        public DataTable getAllChildDeptByOrgID(int orgid,decimal domain_id,bool flag)
        {
            DataTable alldt = null;
            DataTable dt = null;
            string sql = "select * from ORGANIZATION where DOMAIN_ID='"+domain_id+"'";
            alldt = Jumpton.Data.SqlData.OpenSql(sql).Tables[0];//域所有部门
            DataRow[] drs = alldt.Select(" ParentID=" + orgid);//筛选出第一层子部门
            dt = alldt.Clone();
            foreach (DataRow dr in drs)
            {
                dt.ImportRow(dr);
            }
            dt = getChildDept(alldt,dt,drs);
            if (flag)//包涵传入的部门
            {
                drs = alldt.Select(" ID=" + orgid);
                foreach (DataRow dr in drs)
                {
                    dt.ImportRow(dr);
                }
            }

            return dt;
        }

        private DataTable getChildDept(DataTable sdt,DataTable odt,DataRow[] datarow)
        {

            foreach (DataRow dr in datarow)
            {
                DataRow[] drs= sdt.Select(" ParentID=" + dr["ID"]);
                foreach (DataRow drw in drs)
                {
                    odt.ImportRow(drw);//添加查询出的子部门
                }
               
                getChildDept(sdt, odt,drs);//递归查询子部门
            }


            return odt;
        }

        /// <summary>
        /// 根据部门id获取当前部门和所有子部门的人员信息
        /// </summary>
        /// <param name="orgid">父部门id</param>
        /// <param name="domain_id">域id</param>
        /// <param name="flag">是否包涵当前部门</param>
        /// <returns>返回用户表</returns>
        public DataTable getAllChildUsersByOrgID(int orgid, decimal domain_id,bool flag)
        {
            DataTable alldt = null;
            DataTable dt = null;
            DataTable deptdt = null;

            deptdt = getAllChildDeptByOrgID(orgid, domain_id, flag);
            string sql = @"select * from users where DOMAIN_ID='" + domain_id + "'";
            alldt = Jumpton.Data.SqlData.OpenSql(sql).Tables[0];//域所有用户
            dt = alldt.Clone();
            foreach (DataRow dr in deptdt.Rows)
            {
                DataRow[] drs =  alldt.Select(" org_id =" + dr["ID"]);
                foreach (DataRow drw in drs)
                {
                    dt.ImportRow(drw);
                }
            }
            return dt;
        }

        /// <summary>
        /// 根据部门id获取当前部门和所有子部门的销售代表人员信息
        /// </summary>
        /// <param name="orgid">父部门id</param>
        /// <param name="domain_id">域id</param>
        /// <param name="flag">是否包涵当前部门</param>
        /// <returns>返回用户表</returns>
        public DataTable getAllChildSalesByOrgID(int orgid, decimal domain_id, bool flag)
        {
            DataTable alldt = null;
            DataTable dt = null;
            DataTable deptdt = null;

            deptdt = getAllChildDeptByOrgID(orgid, domain_id, flag);
            string sql = @"select u.*,p.name from users u inner join persons p on p.id=u.person_id where u.person_id in(
select id from persons p
inner join DictionaryItems di on p.position=di.code and p.domain_id=di.domain_id
inner join Dictionary d on d.dictionaryid=di.dictionaryid
where d.code='SALESPOSITION' and p.active=1 and d.active=1 and di.active=1 and p.domain_id=" + domain_id + ")";
            alldt = Jumpton.Data.SqlData.OpenSql(sql).Tables[0];//域所有销售代表用户
            dt = alldt.Clone();
            foreach (DataRow dr in deptdt.Rows)
            {
                DataRow[] drs = alldt.Select(" org_id =" + dr["ID"]);
                foreach (DataRow drw in drs)
                {
                    dt.ImportRow(drw);
                }
            }
            return dt;
        }


        public DataTable getUserInfo(string str)
        {
            return Jumpton.Data.SqlData.OpenSql(str).Tables[0];
        }
    }
}
